package alibobo.util.date;

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;

import org.apache.commons.lang.StringUtils;

public class DateRange {

	protected Date from, to;
	boolean stepByMonth = false;
	boolean forward = true;

	public DateRange(Date from, Date to, boolean isMonth, String dir) {
		this.from = from;
		this.to = to;

		stepByMonth = isMonth;
		if (StringUtils.isNotBlank(dir)) {
			if (dir.toLowerCase().startsWith("f"))
				forward = true;
			else
				forward = false;
		}
	}

	public Iterator<Date> getIterator() {
		DateRangeIterator di = new DateRangeIterator();
		di.setDateRange(this);
		return di;
	}

	class DateRangeIterator implements Iterator<Date> {

		Date pt;
		DateRange dateRange;

		protected int stepField;

		@Override
		public boolean hasNext() {
			Date npt;
			if (dateRange.forward) {
				npt = DateUtils.forward(pt, 1, stepField);
				if (npt.after(dateRange.to)) {
					if (dateRange.stepByMonth)
						if (DateUtils.isSameMonth(npt, to))
							return true;
					return false;
				}
			} else {
				npt = DateUtils.backward(pt, 1, stepField);
				if (npt.before(dateRange.from)) {
					if (dateRange.stepByMonth)
						if (DateUtils.isSameMonth(npt, from))
							return true;
					return false;
				}
			}
			return true;
		}

		@Override
		public Date next() {
			if (dateRange.forward) {
				pt = DateUtils.forward(pt, 1, stepField);
				return pt;
			} else {
				pt = DateUtils.backward(pt, 1, stepField);
				return pt;
			}
		}

		@Override
		public void remove() {

		}

		public void setDateRange(DateRange dateRange) {

			this.dateRange = dateRange;
			if (dateRange.stepByMonth)
				stepField = Calendar.MONTH;
			else
				stepField = Calendar.DAY_OF_MONTH;

			forward = dateRange.forward;
			if (forward) {
				pt = DateUtils.backward(dateRange.from, 1, stepField);

			} else {
				pt = DateUtils.forward(dateRange.to, 1, stepField);
			}
		}
	}

}
